package com.dzsw.netty.websocket;

import com.dzsw.netty.websocket.protocal.CProtocol;
import com.dzsw.netty.websocket.util.ProtobufUtil;
import io.netty.channel.*;
import io.netty.handler.codec.http.websocketx.PingWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketClientProtocolHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

@Slf4j
@ChannelHandler.Sharable
public class WebSocketClientHandler extends ChannelInboundHandlerAdapter {

    public static WebSocketClientHandler INSTANCE = new WebSocketClientHandler();

    public static ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(50);

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof WebSocketClientProtocolHandler.ClientHandshakeStateEvent) {
            WebSocketClientProtocolHandler.ClientHandshakeStateEvent event = (WebSocketClientProtocolHandler.ClientHandshakeStateEvent)evt;
            if (event.ordinal() == WebSocketClientProtocolHandler.ClientHandshakeStateEvent.HANDSHAKE_COMPLETE.ordinal()) {

//                ctx.pipeline().addLast("PingPongHandler", PingPongHandler.INSTANCE);
                ctx.pipeline().addLast("BinaryFrameHandler", BinaryFrameHandler.INSTANCE);
                ctx.pipeline().addLast("HeartbeatHandler", HeartbeatHandler.INSTANCE);
                ctx.pipeline().addLast("RequestHandler", RequestHandler.INSTANCE);
                log.info("addLast ok.");

                ScheduledFuture<?> heartbeatTask = scheduler.scheduleAtFixedRate(()-> {
                    CProtocol.Message msg = ProtobufUtil.createHeartbeat();
                    ProtobufUtil.sendBinaryMessage(ctx, msg.toByteArray(), false);
                }, 5, 10, TimeUnit.SECONDS);

                ctx.channel().closeFuture().addListener((ChannelFuture future) -> {
                    heartbeatTask.cancel(true);
                });
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }
}
